<template>
  <div id="app">
    <div id="controls">
      <div class="control-group">
        <button @click="clearCanvas" class="control-button">清除</button>
        <label for="colorPicker" class="control-label">颜色:</label>
        <input type="color" id="colorPicker" v-model="color" class="control-input" />
      </div>
      <div class="control-group">
        <label for="brushSize" class="control-label">笔刷大小:</label>
        <input type="range" id="brushSize" min="1" max="50" v-model.number="brushSize" class="control-range" />
      </div>
      <div class="control-group">
        <label for="drawMode" class="control-label">模式:</label>
        <select id="drawMode" v-model="drawMode" class="control-select">
          <option value="freehand">自由绘</option>
          <option value="line">直线</option>
          <option value="curve">曲线</option>
          <option value="rectangle">矩形</option>
          <option value="square">正方形</option>
          <option value="circle">圆形</option>
        </select>
      </div>
      <div class="control-group">
        <button @click="saveImage" class="control-button">保存</button>
      </div>
      <div class="control-group">
        <label for="backgroundImage" class="control-label">背景图片:</label>
        <input type="file" id="backgroundImage" accept="image/*" @change="uploadBackgroundImage" class="control-file" />
      </div>
      <div class="control-group">
        <button @click="generateVR" class="control-button">生成VR</button>
      </div>
    </div>
    <canvas ref="drawingCanvas" width="800" height="600"></canvas>
  </div>
</template>

<script>
import { ref, onMounted, onUnmounted } from 'vue';
import { useRouter } from 'vue-router';
import {ElMessage} from "element-plus";

export default {
  name: 'App',
  setup() {
    const router = useRouter();
    const drawingCanvas = ref(null);
    const ctx = ref(null);
    const isDrawing = ref(false);
    const color = ref('#000000');
    const brushSize = ref(5);
    const drawMode = ref('freehand');
    let startPoint = { x: 0, y: 0 };
    const backgroundImage = ref(null);
    const imageUrl = ref(null);

    onMounted(() => {
      if (drawingCanvas.value) {
        ctx.value = drawingCanvas.value.getContext('2d');

        // 设置初始画布背景色
        ctx.value.fillStyle = '#ffffff';
        ctx.value.fillRect(0, 0, drawingCanvas.value.width, drawingCanvas.value.height);

        // 添加鼠标事件监听器
        drawingCanvas.value.addEventListener('mousedown', startDrawing);
        drawingCanvas.value.addEventListener('mousemove', draw);
        drawingCanvas.value.addEventListener('mouseup', stopDrawing);
        drawingCanvas.value.addEventListener('mouseout', stopDrawing);
      }
    });

    onUnmounted(() => {
      if (drawingCanvas.value) {
        // 移除事件监听器
        drawingCanvas.value.removeEventListener('mousedown', startDrawing);
        drawingCanvas.value.removeEventListener('mousemove', draw);
        drawingCanvas.value.removeEventListener('mouseup', stopDrawing);
        drawingCanvas.value.removeEventListener('mouseout', stopDrawing);
      }
    });

    const startDrawing = (e) => {
      isDrawing.value = true;
      startPoint.x = e.offsetX;
      startPoint.y = e.offsetY;
      if (drawMode.value === 'freehand') {
        ctx.value.beginPath();
        ctx.value.moveTo(startPoint.x, startPoint.y);
      }
    };

    const stopDrawing = () => {
      isDrawing.value = false;
      if (drawMode.value === 'line' || drawMode.value === 'curve' || drawMode.value === 'rectangle' || drawMode.value === 'square' || drawMode.value === 'circle') {
        drawShape();
      }
      ctx.value.beginPath();
    };

    const draw = (e) => {
      if (!isDrawing.value) return;
      ctx.value.lineWidth = brushSize.value;
      ctx.value.lineCap = 'round';
      ctx.value.strokeStyle = color.value;

      if (drawMode.value === 'freehand') {
        ctx.value.lineTo(e.offsetX, e.offsetY);
        ctx.value.stroke();
        ctx.value.beginPath();
        ctx.value.moveTo(e.offsetX, e.offsetY);
      }
    };

    const drawShape = () => {
      const endPoint = { x: event.offsetX, y: event.offsetY };
      ctx.value.beginPath();
      ctx.value.strokeStyle = color.value;
      ctx.value.lineWidth = brushSize.value;

      if (drawMode.value === 'line') {
        ctx.value.moveTo(startPoint.x, startPoint.y);
        ctx.value.lineTo(endPoint.x, endPoint.y);
      } else if (drawMode.value === 'curve') {
        const cp1x = (startPoint.x + endPoint.x) / 2;
        const cp1y = startPoint.y;
        const cp2x = (startPoint.x + endPoint.x) / 2;
        const cp2y = endPoint.y;
        ctx.value.moveTo(startPoint.x, startPoint.y);
        ctx.value.bezierCurveTo(cp1x, cp1y, cp2x, cp2y, endPoint.x, endPoint.y);
      } else if (drawMode.value === 'rectangle') {
        const width = endPoint.x - startPoint.x;
        const height = endPoint.y - startPoint.y;
        ctx.value.rect(startPoint.x, startPoint.y, width, height);
      } else if (drawMode.value === 'square') {
        const size = Math.max(Math.abs(endPoint.x - startPoint.x), Math.abs(endPoint.y - startPoint.y));
        const offsetX = endPoint.x > startPoint.x ? 0 : -size;
        const offsetY = endPoint.y > startPoint.y ? 0 : -size;
        ctx.value.rect(startPoint.x + offsetX, startPoint.y + offsetY, size, size);
      } else if (drawMode.value === 'circle') {
        const radius = Math.sqrt(Math.pow(endPoint.x - startPoint.x, 2) + Math.pow(endPoint.y - startPoint.y, 2));
        ctx.value.arc(startPoint.x, startPoint.y, radius, 0, 2 * Math.PI);
      }

      ctx.value.stroke();
    };

    const clearCanvas = () => {
      ctx.value.clearRect(0, 0, drawingCanvas.value.width, drawingCanvas.value.height);
      // 重新设置背景图片或背景色
      if (backgroundImage.value) {
        ctx.value.drawImage(backgroundImage.value, 0, 0, drawingCanvas.value.width, drawingCanvas.value.height);
      } else {
        ctx.value.fillStyle = '#ffffff';
        ctx.value.fillRect(0, 0, drawingCanvas.value.width, drawingCanvas.value.height);
      }
    };

    const saveImage = () => {
      // 获取 canvas 上的图片数据
      const imageData = drawingCanvas.value.toDataURL('image/png');

      // 转换为 Base64 编码的图像数据
      const base64Image = imageData.split(',')[1]; // 去除前缀部分 (data:image/png;base64,)

      // 创建一个 JSON 对象，包含图片数据
      const requestData = {
        image: base64Image
      };

      // 使用 fetch 发送 POST 请求
      fetch('/api/api/upload-image', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization':'60d657f606d9448587779e68e80b975a' // token要是活的！！！
        },
        body: JSON.stringify(requestData)
      })
        .then(response => response.json()) // 假设后端返回 JSON 格式的响应
        .then(data => {
          if (data.message.includes("成功")) {
            console.log('图片上传成功', data);
            ElMessage.success(data.message)
          } else {
            console.error('图片上传失败', data);
            ElMessage.error(data.message)
          }
        })
        .catch(error => {
          console.error('上传错误:', error);
        });
    };

    const uploadBackgroundImage = (event) => {
      const file = event.target.files[0];
      if (file) {
        const reader = new FileReader();
        reader.onload = (e) => {
          backgroundImage.value = new Image();
          backgroundImage.value.src = e.target.result;
          backgroundImage.value.onload = () => {
            ctx.value.clearRect(0, 0, drawingCanvas.value.width, drawingCanvas.value.height);
            ctx.value.drawImage(backgroundImage.value, 0, 0, drawingCanvas.value.width, drawingCanvas.value.height);
          };
        };
        reader.readAsDataURL(file);
      }
    };

    const generateVR = () => {
      // 获取 canvas 内容并转换为 URL
      imageUrl.value = drawingCanvas.value.toDataURL('image/png');
      // 导航到全景图组件并传递图片 URL
      router.push({ path: '/panorama', query: { imageUrl: imageUrl.value } });
    };

    return {
      drawingCanvas,
      color,
      brushSize,
      drawMode,
      clearCanvas,
      saveImage,
      uploadBackgroundImage,
      generateVR,
    };
  },
};
</script>

<style>

#controls {
  position: fixed;
  top: 10px;
  left: 50%;
  transform: translateX(-50%);
  background-color: rgba(255, 255, 255, 0.9);
  padding: 15px;
  border-radius: 10px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
  gap: 15px;
  z-index: 10;
  width: 90%;
  max-width: 800px;
}

.control-group {
  display: flex;
  flex-direction: row;
  align-items: center;
}

.control-label {
  font-weight: bold;
  margin-right: 10px;
}

.control-input,
.control-range,
.control-select,
.control-file {
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 5px;
  outline: none;
  transition: border-color 0.2s ease-in-out;
}

.control-input:focus,
.control-range:focus,
.control-select:focus,
.control-file:focus {
  border-color: #007bff;
}

.control-button {
  padding: 10px 20px;
  background-color: #007bff;
  color: white;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  transition: background-color 0.2s ease-in-out;
  margin-left: auto;
}

.control-button:hover {
  background-color: #0056b3;
}

canvas {
  border: 2px solid #ccc;
  background-color: #fff;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
  transition: transform 0.2s ease-in-out;
  margin-top: 60px; /* Adjust based on controls height */
  width: 100%;
  max-width: 800px;
  height: calc(100vh - 80px); /* Full height minus control panel height */
}

canvas:hover {
  transform: scale(1.02);
}

@media (max-width: 768px) {
  #controls {
    grid-template-columns: 1fr;
    width: 95%;
  }

  .control-group {
    flex-direction: column;
    align-items: flex-start;
  }

  .control-label {
    margin-bottom: 5px;
    margin-right: 0;
  }

  .control-button {
    margin-left: 0;
  }

  canvas {
    height: calc(100vh - 100px); /* Adjust for smaller screens */
  }
}
</style>